﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using StyleMVVM.Utilities;

namespace StyleMVVM.UnitTests.Utilities
{
	[TestClass]
	public class CacheManagerTests
	{
		[TestMethod]
		public void BasicAbsoluteCacheTest()
		{
			CacheManager manager = new CacheManager();

			manager.CollectionFrequency = new TimeSpan(0, 0, 0, 0, 500);

			object newCacheObject = new object();

			manager.AddWithAbsoluteExpireTime("TestKey", newCacheObject, DateTime.Now.AddSeconds(5));

			Assert.AreEqual(newCacheObject, manager.GetValue("TestKey"));

			AutoResetEvent resetEvent = new AutoResetEvent(false);

			resetEvent.WaitOne(2000);

			Assert.AreEqual(newCacheObject, manager.GetValue("TestKey"));

			resetEvent.WaitOne(4000);

			Assert.IsNull(manager.GetValue("TestKey"));
		}

		[TestMethod]
		public void BasicSlidingCacheTest()
		{
			CacheManager manager = new CacheManager();

			manager.CollectionFrequency = new TimeSpan(0, 0, 0, 0, 500);

			object newCacheObject = new object();

			manager.AddWithSlidingExpireTime("TestKey", newCacheObject, new TimeSpan(0, 0, 3));

			Assert.AreEqual(newCacheObject, manager.GetValue("TestKey"));

			AutoResetEvent resetEvent = new AutoResetEvent(false);

			for (int i = 0; i < 20; i++)
			{
				resetEvent.WaitOne(500);

				Assert.AreEqual(newCacheObject, manager.GetValue("TestKey"));
			}

			resetEvent.WaitOne(5000);

			Assert.IsNull(manager.GetValue("TestKey"));
		}
	}
}